package com.ishanggang.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;

public class GaoDeLatAndLngUtil {
    public static final String AK = "e6ea2948e203aae3d89d1867f05f05db";
    public static final String LNG = "lng";
    public static final String LAT = "lat";
    /**
     * 高德地图通过地址获取经纬度
     */
    public static Map<String, String> addressToLngAndLag(String address) {
        Map<String, String> map = new HashMap<String, String>();
        String geturl = "http://restapi.amap.com/v3/geocode/geo?key="+AK+"&address=" + address;
        String location = "";
        try {
            URL url = new URL(geturl);    // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            JSONObject a = JSON.parseObject(sb.toString());
            JSONArray sddressArr = JSON.parseArray(a.get("geocodes").toString());
            if (sddressArr.size() == 0) return null;
            JSONObject c = JSON.parseObject(sddressArr.get(0).toString());
            location = c.get("location").toString();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("失败!");
        }
        return stringToMap(location);
    }

    public static Map<String, String> stringToMap(String LngLat) {
        Map<String, String> map = new HashMap<String, String>();
        String[] strArr = LngLat.split("\\,");
        map.put(LNG, strArr[0]);
        map.put(LAT, strArr[1]);
        return map;
    }

    public static void main(String[] args) {
        Timestamp creationDate = Timestamp.valueOf("2022-07-10 13:29:12");
        LocalDate localDate = Instant.ofEpochMilli(creationDate.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
        System.out.println(localDate);

    }
}
